package com.jinghang.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;

import java.util.ArrayList;
import java.util.List;

/**
 * description:
 * author: xiaoxu
 * createTime: 2016-03-22 21:28
 **/
public class _010RedisShardedPool {

    static Logger log = LoggerFactory.getLogger(_010RedisShardedPool.class);

    private static ShardedJedisPool pool;//sharded jedis连接池
    private static Integer maxTotal = 2; //最大连接数
    private static Integer maxIdle = 1;//在jedispool中最大的idle状态(空闲的)的jedis实例的个数
    private static Integer minIdle = 1;//在jedispool中最小的idle状态(空闲的)的jedis实例的个数

    private static Boolean testOnBorrow = Boolean.parseBoolean( "true");//在borrow一个jedis实例的时候，是否要进行验证操作，如果赋值true。则得到的jedis实例肯定是可以用的。
    private static Boolean testOnReturn = Boolean.parseBoolean( "true");//在return一个jedis实例的时候，是否要进行验证操作，如果赋值true。则放回jedispool的jedis实例肯定是可以用的。

    private static String redis1Ip = "hadoop000";
    private static Integer redis1Port = 6379;

    private static String redis2Ip = "hadoop001";
    private static Integer redis2Port = 6379;


    private static void initPool() {
        JedisPoolConfig config = new JedisPoolConfig();

        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);

        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        config.setMaxWaitMillis(2000);

        config.setBlockWhenExhausted(true);//连接耗尽的时候，是否阻塞，false会抛出异常，true阻塞直到超时。默认为true。

        JedisShardInfo info1 = new JedisShardInfo(redis1Ip, redis1Port, 5000 * 2);

        JedisShardInfo info2 = new JedisShardInfo(redis2Ip, redis2Port, 5000 * 2);


        List<JedisShardInfo> jedisShardInfoList = new ArrayList<JedisShardInfo>(4);

        jedisShardInfoList.add(info1);
        //jedisShardInfoList.add(info2);

        pool = new ShardedJedisPool(config, jedisShardInfoList, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);
    }

    //类被加载的时候，执行静态代码块
    static {
        initPool();
    }

    public static ShardedJedis getJedis() {
        return pool.getResource();
    }


    public static void returnBrokenResource(ShardedJedis jedis) {
        pool.returnBrokenResource(jedis);
    }


    public static void returnResource(ShardedJedis jedis) {
        pool.returnResource(jedis);
    }


    public static void main(String[] args) {
        ShardedJedis jedis = pool.getResource();

        for (int i = 0; i < 500; i++) {
            //jedis.set("key"+i,"value"+i);
            jedis.get("key"+i);
            log.info("数量"+i+jedis.get("key"+i));
        }
        returnResource(jedis);

        //        pool.destroy();//临时调用，销毁连接池中的所有连接
        System.out.println("program is end");


    }

}
